package com.xky.ui.module.productManagement.delete;

import com.xky.utils.DBUtils;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DeleteProduct extends JFrame {
    // 定义确认删除的安全字符串
    private static final String CONFIRM_CODE = "DELETE-ALL-CONFIRM";
    
    public DeleteProduct(){
        setTitle("删除界面");
        setSize(280,200); // 增加高度以容纳新按钮
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        init();
        setVisible(true);
    }

    void init(){
        setLayout(new BorderLayout());
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.Y_AXIS)); // 使用BoxLayout纵向排列组件

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        JLabel jLabel = new JLabel("请输入你要删除的商品的ID:", SwingConstants.CENTER);
        jLabel.setFont(new Font("黑体", Font.BOLD, 20));
        titlePanel.add(jLabel);
        jPanel.add(titlePanel);

        // 创建输入面板
        JPanel inputPanel = new JPanel();
        JTextField jTextField = new JTextField(20);
        jTextField.setPreferredSize(new Dimension(250, 30));
        inputPanel.add(jTextField);
        jPanel.add(inputPanel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 5));
        
        JButton jButton = new JButton("删除");
        jButton.setFont(new Font("黑体", Font.BOLD, 20));
        jButton.setBorderPainted(false);
        jButton.setBackground(Color.PINK);
        jButton.setPreferredSize(new Dimension(100, 30));
        buttonPanel.add(jButton);

        JButton jButton1 = new JButton("取消");
        jButton1.setFont(new Font("黑体", Font.BOLD, 20));
        jButton1.setBorderPainted(false);
        jButton1.setBackground(Color.PINK);
        jButton1.setPreferredSize(new Dimension(100, 30));
        buttonPanel.add(jButton1);
        
        jPanel.add(buttonPanel);
        
        // 创建删除所有商品的按钮面板
        JPanel deleteAllPanel = new JPanel();
        JButton deleteAllButton = new JButton("删除所有商品");
        deleteAllButton.setFont(new Font("黑体", Font.BOLD, 20));
        deleteAllButton.setBorderPainted(false);
        deleteAllButton.setBackground(Color.RED);
        deleteAllButton.setForeground(Color.WHITE);
        deleteAllButton.setPreferredSize(new Dimension(200, 30));
        deleteAllPanel.add(deleteAllButton);
        
        jPanel.add(deleteAllPanel);

        add(jPanel, BorderLayout.CENTER);

        // 单个商品删除按钮事件
        jButton.addActionListener(e -> {
            String id = jTextField.getText().trim();
            System.out.println("你点击了确定按钮！");
            if (id.isEmpty()){
                JOptionPane.showMessageDialog(DeleteProduct.this, "请输入你要删除的商品的ID", "提示", JOptionPane.WARNING_MESSAGE);
               return;
            }
            int i = JOptionPane.showConfirmDialog(DeleteProduct.this, "你确定要删除该商品信息吗？", "删除提示", JOptionPane.YES_NO_OPTION);
            if (i == JOptionPane.YES_OPTION){
                if (selectById(id)){
                    deleteProduct(id);
                    JOptionPane.showMessageDialog(DeleteProduct.this, "该商品信息删除成功！", "成功提示", JOptionPane.INFORMATION_MESSAGE);
                    setVisible(false);
                } else {
                    JOptionPane.showMessageDialog(DeleteProduct.this, "找不到该商品ID,信息删除失败!", "失败提示", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 取消按钮事件
        jButton1.addActionListener(e -> {
            dispose();
        });
        
        // 删除所有商品按钮事件
        deleteAllButton.addActionListener(e -> {
            // 显示警告对话框，要求用户确认
            int option = JOptionPane.showConfirmDialog(
                DeleteProduct.this,
                "警告：此操作将删除所有商品信息，且无法恢复！\n确定要继续吗？",
                "危险操作确认",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE
            );
            
            if (option == JOptionPane.YES_OPTION) {
                // 创建输入对话框，要求用户输入安全确认码
                JPanel confirmPanel = new JPanel();
                confirmPanel.setLayout(new BoxLayout(confirmPanel, BoxLayout.Y_AXIS));
                confirmPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
                
                JLabel instructionLabel = new JLabel("为确保安全，请输入以下确认码：");
                instructionLabel.setForeground(Color.RED);
                instructionLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(instructionLabel);
                confirmPanel.add(Box.createVerticalStrut(10));
                
                // 使用JTextField显示确认码，允许选择和复制
                JTextField codeField = new JTextField(CONFIRM_CODE);
                codeField.setEditable(false);
                codeField.setFont(new Font("Monospaced", Font.BOLD, 14));
                codeField.setBackground(new Color(240, 240, 240));
                codeField.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(codeField);
                
                // 添加复制按钮
                JButton copyButton = new JButton("复制确认码");
                copyButton.setAlignmentX(Component.LEFT_ALIGNMENT);
                copyButton.addActionListener(evt -> {
                    StringSelection stringSelection = new StringSelection(CONFIRM_CODE);
                    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                    clipboard.setContents(stringSelection, null);
                });
                confirmPanel.add(Box.createVerticalStrut(5));
                confirmPanel.add(copyButton);
                confirmPanel.add(Box.createVerticalStrut(15));
                
                JLabel inputLabel = new JLabel("请在下方输入确认码：");
                inputLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(inputLabel);
                confirmPanel.add(Box.createVerticalStrut(5));
                
                JTextField confirmField = new JTextField(20);
                confirmField.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(confirmField);
                confirmPanel.add(Box.createVerticalStrut(10));
                
                JLabel warningLabel = new JLabel("请注意：此操作不可撤销！");
                warningLabel.setForeground(Color.RED);
                warningLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                confirmPanel.add(warningLabel);
                
                int result = JOptionPane.showConfirmDialog(
                    DeleteProduct.this,
                    confirmPanel,
                    "安全确认",
                    JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.WARNING_MESSAGE
                );
                
                // 如果用户点击确定，检查输入的确认码是否正确
                if (result == JOptionPane.OK_OPTION) {
                    String userInput = confirmField.getText().trim();
                    
                    if (CONFIRM_CODE.equals(userInput)) {
                        // 执行删除所有商品的操作
                        if (deleteAllProducts()) {
                            JOptionPane.showMessageDialog(
                                DeleteProduct.this,
                                "所有商品信息已成功删除！",
                                "操作成功",
                                JOptionPane.INFORMATION_MESSAGE
                            );
                            dispose();
                        } else {
                            JOptionPane.showMessageDialog(
                                DeleteProduct.this,
                                "删除所有商品信息失败，请检查数据库连接或权限！",
                                "操作失败",
                                JOptionPane.ERROR_MESSAGE
                            );
                        }
                    } else {
                        JOptionPane.showMessageDialog(
                            DeleteProduct.this,
                            "确认码输入错误，操作已取消！",
                            "验证失败",
                            JOptionPane.ERROR_MESSAGE
                        );
                    }
                }
            }
        });
    }
    
    /**
     * 删除单个商品
     * @param productId 商品ID
     * @return 是否删除成功
     */
    public boolean deleteProduct(String productId){
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("DELETE FROM products WHERE product_id = ?");
            preparedStatement.setString(1, productId);
            int i = preparedStatement.executeUpdate();
            if (i > 0){
                System.out.println("影响行数为" + i + "删除成功！");
                return true;
            } else {
                System.out.println("影响行数为" + i + "删除失败！");
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }
    
    /**
     * 删除所有商品信息
     * @return 是否删除成功
     */
    public boolean deleteAllProducts() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("DELETE FROM products");
            int rowsAffected = preparedStatement.executeUpdate();
            System.out.println("删除了" + rowsAffected + "条商品记录");
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, null);
        }
    }

    public Boolean selectById(String productId){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtils.getConnection();
            preparedStatement = connection.prepareStatement("SELECT * FROM products WHERE product_id = ?");
            preparedStatement.setString(1, productId);
            resultSet = preparedStatement.executeQuery();

            return resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBUtils.closeAll(connection, preparedStatement, resultSet);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(DeleteProduct::new);
    }
}
